package com.mini.mybatis.session.defaults;

import com.mini.mybatis.executor.Executor;
import com.mini.mybatis.executor.SimpleExecutor;
import com.mini.mybatis.session.Configuration;
import com.mini.mybatis.session.SqlSession;
import com.mini.mybatis.session.SqlSessionFactory;

import java.sql.SQLException;

/**
 * 默认SqlSession工厂实现
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {
    
    private final Configuration configuration;
    
    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }
    
    @Override
    public SqlSession openSession() {
        return openSession(false);
    }
    
    @Override
    public SqlSession openSession(boolean autoCommit) {
        return openSessionFromDataSource(autoCommit);
    }
    
    @Override
    public Configuration getConfiguration() {
        return configuration;
    }
    
    /**
     * 从数据源打开SqlSession
     */
    private SqlSession openSessionFromDataSource(boolean autoCommit) {
        try {
            // 创建执行器
            Executor executor = new SimpleExecutor(configuration, autoCommit);
            
            // 创建DefaultSqlSession
            return new DefaultSqlSession(configuration, executor, autoCommit);
        } catch (Exception e) {
            throw new RuntimeException("创建SqlSession时出错。原因: " + e, e);
        }
    }
}